import json
import os
import sys

from common.content_type import ContentType
from common.time_bdp import time_bdp
from core.result_base import ResultBase
from api.folder import folder
from common.logger import logger
from common.user_agent import useragent
import urllib3
urllib3.disable_warnings()

BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(BASE_PATH)


def env_clear(access_token,tree_type):
    '''
    删除所在域的下面所有的工作表文件夹
    '''
    _t = time_bdp.time_stamp_13()
    _xsrf = ""
    tree_type = tree_type
    tb_id = ""
    folder_list = []
    folder_newtree_result = folder_newtree(access_token,_t,_xsrf,tree_type,tb_id,folder_list)
    #获取所有的工作表文件夹id
    folder_newtree_payload = folder_newtree_result.payload
    folder_id_list = folder_newtree_payload["result"]["folder_list"]
    for folder_id in folder_id_list:
        really_folder_id = folder_id["folder_id"]
        if really_folder_id == "folder_root":
            pass
        else:
            mode = "0"
            folder_delete(access_token,really_folder_id,mode)

    # key = "folder_id"
    # folder_id_list = json_utils.get_list(folder_newtree_payload,key)
    # print(folder_id_list)
    # ["result"]["folder_list"]["folder_id"]
    # for folder_id in folder_id_list:
    #     mode = "0"
    #     folder_delete(access_token,folder_id,mode)

def folder_create(access_token,name,parent_id="folder_root",_xsrf=None,_t=time_bdp.time_stamp_13()):
    """
    创建工作表文件夹
    :param _t: 13位的时间戳
    :param name: 文件夹名称
    :param parent_id : 父文件夹，为空或者是传的是错误的代表是根目录，不为空则代表有父目录
    :param _xsrf :
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    payload = {
        "_t": _t,
        "name": name,
        "parent_id": parent_id,
        "_xsrf":_xsrf
    }

    headers = {
        "Content-Type": ContentType.APPLICATION_JSON.value,
        "User-Agent": useragent.get_user_agent_one()
   }

    cookies = {
        "access_token":access_token
    }

    res = folder.create(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("创建工作表文件夹 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result



#
# def folder_create_level(access_token,level_number,parent_id="folder_root",_xsrf=None,_t=time_bdp.time_stamp_13()):
#     """
#     创建工作表文件夹
#     :param _t: 13位的时间戳
#     :param name: 文件夹名称
#     :param parent_id : 父文件夹，为空或者是传的是错误的代表是根目录，不为空则代表有父目录
#     :param _xsrf :
#     :return: 自定义的关键字返回结果 result
#     """
#     result = ResultBase()
#     payload = {
#         "_t": _t,
#         "name": name,
#         "parent_id": parent_id,
#         "_xsrf":_xsrf
#     }
#
#     headers = {
#         "Content-Type": ContentType.APPLICATION_JSON.value,
#         "User-Agent": useragent.get_user_agent_one()
#    }
#
#     cookies = {
#         "access_token":access_token
#     }
#
#     res = folder.create(params=payload, headers=headers,cookies=cookies)
#     result.success = False
#     if res.json()["status"] == "0":
#         result.success = True
#     else:
#         result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
#     result.payload = res.json()
#     result.response = res
#     logger.info("创建工作表文件夹 ==>> 返回结果 ==>> {}".format(result.response.text))
#     return result



def project_modify(access_token,_t,name,proj_id,_xsrf):
    """
    编辑文件夹
    :param _t: 13位的时间戳
    :param name: 文件夹名称
    :param proj_id : 要修改的文件夹id
    :param _xsrf :
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    payload = {
        "_t": _t,
        "data":{"name": name},
        "proj_id": proj_id,
        "_xsrf":_xsrf
    }

    header = {
        "Content-Type": "application/json;charset=utf-8"
   }

    res = project.modify(access_token,json=payload, headers=header)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("修改文件夹 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


def folder_newtree(access_token,tb_id,folder_list,tree_type="0",_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    获取所有文件夹和工作表
    :param _t: 13位的时间戳
    :param _xsrf :
    :param tree_type :0是我的(默认)，1是授权的
    :param tb_id :
    :param folder_list :
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    payload = {
        "tb_id":tb_id,
        "folder_list": json.dumps(folder_list),
        "tree_type": tree_type,
        "_t": _t,
        "_xsrf": _xsrf
    }

    headers = {
        "Content-Type": ContentType.APPLICATION_JSON.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token":access_token
    }


    res = folder.newtree(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("newtree ==>> 返回结果 ==>> {}".format(result.response.text))
    return result



def folder_delete(access_token,folder_id,mode=0):
    """
    删除工作表文件夹
    :param folder_id :工作表文件夹ID
    :param mode :0时代表只删除这一层工作表(默认值)，1时代表删除同时删除文件夹和子工作表
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    payload = {
        "folder_id": folder_id,
        "mode":mode
    }

    headers = {
        "Content-Type": ContentType.APPLICATION_JSON.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }


    res = folder.delete(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("删除工作表文件夹 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result



def folder_newfilter(access_token,filter_str,filter_type=0,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    搜索工作表&工作表文件夹
    :param filter_str :工作表文件夹ID
    :param filter_type :0代表工作表（默认值），1代表文件夹
    :param _t :13位的时间戳
    :param _xsrf :
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    payload = {
        "filter_str": filter_str,
        "filter_type":filter_type,
        "_t":_t,
        "_xsrf":_xsrf
    }

    headers = {
        "Content-Type": ContentType.APPLICATION_JSON.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = folder.newfilter(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("newfilter ==>> 返回结果 ==>> {}".format(result.response.text))
    return result

def folder_new_list_only_tb(access_token,folder_id,is_user_id=0,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    搜索文件夹下面的工作表
    :param folder_id :工作表文件夹ID
    :param is_user_id :
    :param _t :13位的时间戳
    :param _xsrf :
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    payload = {
        "folder_id": folder_id,
        "is_user_id":is_user_id,
        "_t":_t,
        "_xsrf":_xsrf
    }

    headers = {
        "Content-Type": ContentType.APPLICATION_JSON.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = folder.new_list_only_tb(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("搜索工作表文件夹下的工作表 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


def folder_change(access_token,tb_id,to_seq,tb_index,to_folder="folder_root",_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    移动工作表
    :param _t: 13位的时间戳
    :param _xsrf :
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    payload = {
        "tb_id": tb_id,
        "to_folder":to_folder,
        "to_seq": to_seq,
        "tb_index": tb_index,
        "_t": _t,
        "_xsrf":_xsrf
    }

    headers = {
        "Content-Type": ContentType.APPLICATION_JSON.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }


    res = folder.change(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("移动工作表 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result



def folder_change_batch(access_token,change_folders,to_folder="folder_root",_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    批量移动工作表
    :param _t: 13位的时间戳
    :param _xsrf :
    :return: 自定义的关键字返回结果 result
    """
    #[{"tb_index":0,"tb_id":"tb_826e3c599ef843b39f52a20220ed3114"}]
    result = ResultBase()
    payload = {
        "change_folders":json.dumps(change_folders),
        "to_folder":to_folder,
        "_t": _t,
        "_xsrf":_xsrf
    }

    headers = {
        "Content-Type": ContentType.APPLICATION_JSON.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = folder.change_batch(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("批量移动工作表 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


